package com.heu.blood.recycle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heu.blood.common.utils.GenerateNumberBySnowFlake;
import com.heu.blood.common.utils.PageUtils;
import com.heu.blood.common.utils.Query;
import com.heu.blood.match.entity.BloodMatchEntity;
import com.heu.blood.match.service.BloodInformationService;
import com.heu.blood.recycle.entity.BloodTrackEntity;
import com.heu.blood.recycle.dao.BloodTrackDao;
import com.heu.blood.recycle.service.BloodTrackService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heu.blood.security.entity.LoginUser;
import com.heu.blood.storge.service.BloodInStorgeService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ysl
 * @since 2023-07-05
 */
@Service
public class BloodTrackServiceImpl extends ServiceImpl<BloodTrackDao, BloodTrackEntity> implements BloodTrackService {

    @Autowired
    BloodInformationService bloodInformationService;
    @Autowired
    BloodInStorgeService bloodInStorgeService;
    @Autowired
    BloodTrackDao bloodTrackDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        //创建BloodTrackEntity对象用于存放查询条件信息
        BloodTrackEntity bloodTrack = new BloodTrackEntity();
        if(Strings.isNotBlank((String)params.get("transfusionId"))){
            bloodTrack.setTransfusionId((String) params.get("transfusionId"));
        }
        if(Strings.isNotBlank((String)params.get("medicalRecordNumber"))){
            bloodTrack.setMedicalRecordNumber((String) params.get("medicalRecordNumber"));
        }
        if(Strings.isNotBlank((String)params.get("bloodId"))){
            bloodTrack.setBloodId((String) params.get("bloodId"));
        }
        if(Strings.isNotBlank((String)params.get("patientId"))){
            bloodTrack.setPatientId((String) params.get("patientId"));
        }
        //添加时间范围条件
        String startTime = null;
        String endTime = null;
        if(Strings.isNotBlank((String)params.get("startTime")))
            startTime = (String)params.get("startTime");
        if(Strings.isNotBlank((String)params.get("endTime")))
            endTime = (String)params.get("endTime");


        //构造条件构造器
        LambdaQueryWrapper<BloodTrackEntity> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.eq(Strings.isNotBlank(bloodTrack.getTransfusionId()),BloodTrackEntity::getTransfusionId,bloodTrack.getTransfusionId())
                    .eq(Strings.isNotBlank(bloodTrack.getMedicalRecordNumber()),BloodTrackEntity::getMedicalRecordNumber,bloodTrack.getMedicalRecordNumber())
                    .eq(Strings.isNotBlank(bloodTrack.getBloodId()),BloodTrackEntity::getBloodId,bloodTrack.getBloodId())
                    .eq(Strings.isNotBlank(bloodTrack.getPatientId()),BloodTrackEntity::getPatientId,bloodTrack.getPatientId())
                    .ge(Strings.isNotBlank(startTime),BloodTrackEntity::getDispatchTime,startTime)
                    .le(Strings.isNotBlank(endTime),BloodTrackEntity::getDispatchTime,endTime)
                    .eq(BloodTrackEntity::getIfShow,1);

        IPage<BloodTrackEntity> page = this.page(
                new Query<BloodTrackEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }



    /**
     * 根据血液ID查询发取血信息
     * @param bloodId
     * @return
     */
    @Override
    public BloodTrackEntity queryByBloodId(String bloodId) {
        //构造构造器
        LambdaQueryWrapper<BloodTrackEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Strings.isNotBlank(bloodId),BloodTrackEntity::getBloodId,bloodId)
                    .eq(BloodTrackEntity::getIfShow,1);
        //返回BloodTrackEntity
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 发血
     * @param bloodTrackEntity
     * @return
     */
    @Override
    public Boolean dispatch(BloodTrackEntity bloodTrackEntity) {

        //输血申请单
//        if(bloodTrackEntity.getTransfusionId() == null){
//            LambdaQueryWrapper<BloodMatchEntity> bloodMatchQueryWrapper = new LambdaQueryWrapper<>();
//        }


        //根据雪花算法生成trackId
        String flag = "BTK"; //BloodTrack
        GenerateNumberBySnowFlake generateNumberBySnowFlake = new GenerateNumberBySnowFlake(Integer.valueOf(bloodTrackEntity.getBloodId()),flag);
        bloodTrackEntity.setTrackId(generateNumberBySnowFlake.genNumberByflag());

        //发血目的默认为“HOSPITALIZATION” -> 住院
        if(bloodTrackEntity.getDispatchPurpose() == null)
            bloodTrackEntity.setDispatchPurpose("HOSPITALIZATION");

        //获取当前线程认证信息
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null && authentication.isAuthenticated()){
            //获取当前用户id、name
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            //写入当前用户信息
            bloodTrackEntity.setDispatcherName(loginUser.getUser().getUserName());
            bloodTrackEntity.setDispatcherId(String.valueOf(loginUser.getUser().getUserId()));
        }

        //发血时间
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format(date);
        try {
            Date time1 = dateFormat.parse(time);
            bloodTrackEntity.setDispatchTime(time1);
        } catch (ParseException e) {
            //
        }

        //更新血液信息表和库存表
        boolean bloodUpdate = bloodInformationService.updateBloodStateByBloodId(bloodTrackEntity.getBloodId(),"BLOOD_TAKEN_UNCOMPLETED");
        boolean strogeUpdate = bloodInStorgeService.updateInStorgeBloodStatebyBloodId(bloodTrackEntity.getBloodId(),"BLOOD_TAKEN_UNCOMPLETED");

        return bloodTrackDao.insert(bloodTrackEntity) == 1 && bloodUpdate && strogeUpdate;
    }

    /**
     * 批量删除
     * @param list
     * @return
     */
    @Override
    public Boolean dispatchBatch(List<BloodTrackEntity> list) {
        Integer count = 0;
        for(BloodTrackEntity a:list){
            if(this.dispatch(a))count++;
        }
        return count == list.size();
    }
}
